<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"
    />
    <title>发布观察者模式</title>
</head>

<body>
    <p>全局-发布-订阅对象</p>
    <p>只能先订阅之后才能再发布</p>

    <div id="release">发布售楼信息</div>
    <script type="text/javascript">
        var Event = (function () {
            var clientList = {},
                listen,
                trigger,
                remove;
            listen = function (key, fn) {
                if (!clientList[key]) {
                    clientList[key] = [];
                }
                clientList[key].push(fn);
            };
            trigger = function () {
                var key = Array.prototype.shift.call(arguments),
                    fns = clientList[key];
                if (!fns || fns.length === 0) {
                    return false;
                }
                for (var i = 0, fn; fn = fns[i++];) {
                    fn.apply(this, arguments);
                }
            };
            remove = function (key, fn) {
                var fns = clientList[key];
                if (!fns) {
                    return false;
                }
                if (!fn) {
                    fns && (fns.length = 0);
                } else {
                    for (var l = fns.length - 1; l >= 0; l--) {
                        var _fn = fns[l];
                        if (_fn === fn) {
                            fns.splice(l, 1);
                        }
                    }
                }
            };
            return {
                listen: listen,
                trigger: trigger,
                remove: remove
            }
        })();
        Event.listen('squareMeter88', function (price) { // 小红订阅消息
            console.log('价格= ' + price); // 输出：'价格=2000000'
        });
        Event.trigger('squareMeter88', 2000000); // 售楼处发布消息
        Event.trigger('squareMeter88', 1000000); // 售楼处发布消息


    </script>

</body>

</html>